#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
# sys.path.append('/opt/work/caffe/python')
sys.path.insert(0, '.')

import random
import argparse
import os
import numpy as np
from collections import OrderedDict
import struct
import cv2
import math
from math import cos, sin
import re
from matplotlib import pyplot as plt

# SLEEP_TIME = 40
SLEEP_TIME = 1

image_base_path = r'/rootfs/media/kasim/Data1/data/VideoCropFace'
out_path = r'/rootfs/media/kasim/Data1/data/VideoCropFace'
image_list_file = r'/rootfs/media/kasim/Data1/data/VideoCropFace/face_image_filter.txt'


def draw_hist(plt, name, xlist, bins):
    if isinstance(xlist, np.ndarray):
        x = xlist
    else:
        x = np.array(xlist)
    n, bins, patches = plt.hist(x, bins, align=u'mid', facecolor='blue', alpha=0.5)
    plt.title('{}: {:.2f} {:.3f} {:.2f} {:.2f}'.format(name, x.mean(), x.std(), x.min(), x.max()))


def show_hist(value_list, min_value=0.0, max_value=1.0, dbin=0.1, dxticks=0.1, title_str='Age'):
    bins = np.linspace(min_value, max_value, int((max_value - min_value) / dbin) + 1)
    xticks = np.linspace(min_value, max_value, int((max_value - min_value) / dxticks) + 1)

    fig = plt.figure(title_str, figsize=(24, 12))
    plt.subplot(111)
    draw_hist(plt, title_str, value_list, bins)
    plt.xticks(xticks)
    plt.tight_layout()
    plt.show()


def show_hist_ex(value_list, bin_count=20, scale=1.0, min_value=None, max_value=None, title_str='Quality', mode=0):
    if isinstance(value_list, np.ndarray):
        values = value_list
    else:
        values = np.array(value_list)
    if scale != 1.0:
        values = values * scale
    if min_value is None:
        min_value = values.min()
        min_value = math.floor(min_value)
    if max_value is None:
        max_value = values.max()
        max_value = math.ceil(max_value)

    diff_value = max_value - min_value
    if mode != 0:
        if bin_count > diff_value:
            bin_count = diff_value
    dxticks = diff_value / bin_count

    show_hist(values, min_value, max_value, dxticks, dxticks, title_str)


def main():
    if not os.path.exists(out_path):
        os.makedirs(out_path)
    os.system('chmod a+wr {}'.format(out_path))

    quality_interval = 5
    scale = 100
    bin_count = scale // quality_interval
    quality_file_list = [[] for _ in range(bin_count)]
    qualitys = []
    with open(image_list_file, 'r') as file:
        for line in file.readlines():
            lines = line.strip().split()
            # file_name = lines[0]
            quality = float(lines[2])
            qualitys.append(quality)
            quality_index = int(quality*scale) // quality_interval
            quality_file_list[quality_index].append(line)

    random.seed(123456)
    for quality_index, file_list in enumerate(quality_file_list):
        quality_start = quality_index * quality_interval
        quality_end = quality_start + quality_interval
        out_file_path = os.path.join(out_path, 'face_image_q{}-{}.txt'.format(quality_start, quality_end))
        with open(out_file_path, 'w') as file:
            random.shuffle(file_list)
            print(out_file_path, len(file_list))
            for file_info in file_list:
                file.write(file_info)
        os.system('chmod a+wr {}'.format(out_file_path))

    show_hist_ex(qualitys, bin_count=bin_count, scale=scale, min_value=0, max_value=scale, title_str='Quality', mode=0)
    print('Finish!')


if __name__ == '__main__':
    main()
